/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pl.elka.gis.main.nodesproviders;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import pl.elka.gis.main.helper.Pair;
import pl.elka.gis.main.node.Node;

/**
 *
 * @author looser
 */
public class XMLFileNodesProvider implements INodesProvider {

    private String xmlFileName;
    
    @Override
    public Set<Node> provideNodes() {
        try{
            Map<String,Node> nodesMap = new HashMap<String, Node>();
           
            DOMParser parser = new DOMParser();
            parser.parse(new File(xmlFileName).getAbsolutePath());
            Document parsedXML = parser.getDocument();
            Element mainElement = parsedXML.getDocumentElement();
            NodeList nodes = mainElement.getElementsByTagName("node");
            for(int i=0;i<nodes.getLength();++i){
                Element nodeElem = (Element) nodes.item(i);
                Node node = getNodeFromElement(nodeElem);
                nodesMap.put(node.getName(),node);
            }

            nodes = mainElement.getElementsByTagName("edge");
            for(int i=0;i<nodes.getLength();++i){
                Element nodeElem = (Element) nodes.item(i);
                Pair<String,String> edge = getEdgeFromElement(nodeElem);
                if(nodesMap.get(edge.fst)==null || nodesMap.get(edge.snd)==null ){
                    throw new Exception("Nieprawidlowa definicja krawedzi " + edge.fst + " -> " + edge.snd);
                }
                Node from = nodesMap.get(edge.fst);
                Node to = nodesMap.get(edge.snd);
                
                from.addAvailableNode(to);
                to.addAvailableNode(from);
            }
            return new HashSet<Node>(nodesMap.values());
        }catch(Exception e){
            throw new RuntimeException(e);
        }        
    }

    private Node getNodeFromElement(Element nodeElem) throws NumberFormatException {
        String name = nodeElem.getAttribute("name");
        String x = nodeElem.getAttribute("x");
        String y = nodeElem.getAttribute("y");

        Node node =
            new Node(
                name,
                Integer.parseInt(x),
                Integer.parseInt(y));
        return node;
    }   

    private Pair<String, String> getEdgeFromElement(Element nodeElem) {     
        String from = nodeElem.getAttribute("from");
        String to = nodeElem.getAttribute("to");

        return new Pair<String, String>(from, to);
    }

     public XMLFileNodesProvider(String xmlFileName) {
        this.xmlFileName = xmlFileName;
    }
}
